package org.liangsy.client.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    private SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); // 初始化雪花算法工具类

    @Override
    public Result register(UserInfoDto userInfo) {
        UserInfo user = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getUsername, userInfo.getUsername()));
        if (user != null) {
            return Result.failed("用户名已存在");
        }
        // 新增密码校验
        if (!isValidPassword(userInfo.getPasswordHash())) {
            return Result.failed("密码包含空格或特殊字符");
        }

        userInfo.setUserId(String.valueOf(idWorker.nextId()));
        userInfo.setCreateDate(System.currentTimeMillis());
        userInfo.setUpdateDate(System.currentTimeMillis());
        userInfo.setStatusCd(ClientLoginConstans.USER_STATUS.ACTIVE);

        boolean success = userInfoMapper.insert(userInfo) > 0;
        if (success) {
            return Result.success("成功");
        } else {
            return Result.failed("注册失败");
        }
    }

    @Override
    public Result login(UserInfoDto info) {
        LambdaQueryWrapper<UserInfo> eq = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUsername, info.getUsername())
                .eq(UserInfo::getPasswordHash, info.getPasswordHash());
        UserInfo userInfo = userInfoMapper.selectOne(eq);

        if (userInfo != null && userInfo.getPasswordHash().equals(info.getPasswordHash())) {
            return Result.success();
        } else {
            return Result.failed("登录失败");
        }
    }

    @Override
    public Result forgetPassword(UserInfoDto info) {
        // 新增密码校验
        if (!isValidPassword(info.getPasswordHash())) {
            return Result.failed("密码包含空格或特殊字符");
        }

        LambdaQueryWrapper<UserInfo> eq = new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getEmail, info.getEmail());
        UserInfo userInfo = userInfoMapper.selectOne(eq);
        if (userInfo != null) {
            userInfo.setPasswordHash(info.getPasswordHash());
            boolean success = userInfoMapper.updateById(userInfo) > 0;
            if (success) {
                return Result.success();
            } else {
                return Result.failed("密码更新失败");
            }
        }
        return Result.failed("用户不存在");
    }


    private boolean isValidPassword(String password) {
        if (password == null) {
            return false;
        }
        // 正则表达式校验是否包含空格或特殊字符
        return password.matches("^[a-zA-Z0-9]+$");
    }
}